package com.poposchool.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.poposchool.project.common.Constants;
import com.poposchool.project.controller.dto.UserDTO;
import com.poposchool.project.entity.Menu;
import com.poposchool.project.entity.TotalUser;
import com.poposchool.project.exception.ServiceException;
import com.poposchool.project.mapper.RoleMapper;
import com.poposchool.project.mapper.RoleToMenuMapper;
import com.poposchool.project.mapper.TotalUserMapper;
import com.poposchool.project.service.ITotalUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poposchool.project.service.MenuService;
import com.poposchool.project.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangjie
 * @since 2022-09-09
 */
@Service
public class TotalUserServiceImpl extends ServiceImpl<TotalUserMapper, TotalUser> implements ITotalUserService {
    @Resource
    TotalUserMapper totalUserMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    RoleToMenuMapper roleToMenuMapper;

    @Resource
    MenuService menuService;

    @Override
    public Page<TotalUser> findPage(Page<TotalUser> objectPage, String username, String city, String province) {
        QueryWrapper<TotalUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(username), "username", username);
        queryWrapper.like(StringUtils.isNotBlank(city), "city", city);
        queryWrapper.like(StringUtils.isNotBlank(province), "province", province);
        return page(objectPage,queryWrapper);
    }

    @Override
    public UserDTO login(UserDTO userDTO) {
        //捕获sql异常
        TotalUser user = null;
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username",userDTO.getUserName());
            user = totalUserMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }

        if (user != null) {
            BeanUtil.copyProperties(user, userDTO, true);
            // 设置token
            String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
            userDTO.setToken(token);
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }


        if (user != null && user.getPassword().equals(userDTO.getPassWord())) {//查询成功
            try {
                BeanUtil.copyProperties(user, userDTO, true);
                //返回前端token
                String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
                userDTO.setToken(token);
                //设置menu
                Integer userStatus = Integer.parseInt(String.valueOf(user.getStatus()));
                String role = roleMapper.getRoleById(userStatus).getFlag();//获得flag
                Integer roleId = roleMapper.getRoleByFlag(role).getId();
                //菜单id
                List<Integer> menusId = roleToMenuMapper.getRoleMenu(roleId);
                //获得所以菜单树状图
                List<Menu> allMenus = menuService.getMenusConstruction();
                List<Menu> menus = new ArrayList<>();

                for (Menu menu : allMenus) {
                    if (menusId.contains(menu.getId())) {//一级的
                        menus.add(menu);
                        List<Menu> children = menu.getChildren();
                        children.removeIf(child -> !menusId.contains(child.getId()));
                    }else {//可能孩子节点有
                        List<Menu> children = menu.getChildren();
                        for(Menu menu1 : children){
                            if (menusId.contains(menu1.getId())){//孩子被选中了
                                menus.add(menu);
                                break;
                            }
                        }
                        children.removeIf(child -> !menusId.contains(child.getId()));
                    }
                }
                userDTO.setMenus(menus);
            } catch (Exception e) {
                log.error(e.getMessage());
                throw new ServiceException(Constants.CODE_500, "系统错误");
            }
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或者密码错误");
        }
    }

    private TotalUser getUserInfo(UserDTO userDTO) {
        QueryWrapper<TotalUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUserName());
        queryWrapper.eq("password", userDTO.getPassWord());
        TotalUser one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }

    @Override
    public TotalUser register(UserDTO userDTO) {
        TotalUser user = null;
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username",userDTO.getUserName());
            user = totalUserMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        if (user == null) {//没有重复的账号
            //把userDTO的信息填入到user中
            user = new TotalUser();
            BeanUtil.copyProperties(userDTO, user, true);
            //注册的都是用户
            user.setCreateTime(LocalDateTime.now());
            totalUserMapper.insert(user);
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已经存在");
        }
        return user;
    }

}
